package com.hunktimes.wholesale.ui.tabs.types

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.hunktimes.wholesale.R
import com.hunktimes.wholesale.base.BaseMainFragment
import com.hunktimes.wholesale.databinding.TitleTabViewpagerBinding
import com.hunktimes.wholesale.ui.pages.JewelListFragment
import com.hunktimes.wholesale.util.Constants
import com.hunktimes.wholesale.util.L

/**
 * Author: Delete
 * Date: 2020/9/16 17:29
 * Description:
 * tab2 tablayout 分類
 *
 */
class JewelTypedFragment : BaseMainFragment(R.layout.title_tab_viewpager) {
    lateinit var viewBinding: TitleTabViewpagerBinding
    override val titleRes: Int
        get() = R.string.title_category

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding = TitleTabViewpagerBinding.bind(view)
    }

    override fun onStart() {
        super.onStart()
        initTabLayout()
    }

    override fun onResume() {
        super.onResume()
        //to fix RecyclerView's last item can not be totally display
        viewBinding.root.post {
            val vpTop = viewBinding.viewPager.top
            val vpBot = viewBinding.viewPager.bottom
            val vpHeight = viewBinding.viewPager.height
            L.d("viewPager top bot height -> [$vpTop - $vpBot - $vpHeight]")
            val layoutParams = viewBinding.viewPager.layoutParams
            layoutParams.height = vpHeight
            viewBinding.viewPager.layoutParams = layoutParams
        }
    }

    val titles = arrayOf(
        "全部", "翡翠", "和田玉", "鑽石彩寶", "珍珠珊瑚", "琥珀蜜蠟",
        "猛犸象象牙", "銀飾", "南紅", "金銀器", "漆器", "瑪瑙", "其它"
    )

    fun initTabLayout() {
        viewBinding.viewPager.adapter = JewelTeypedTabAdatper(this)
        viewBinding.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE

        TabLayoutMediator(viewBinding.tabLayout, viewBinding.viewPager) { tab, position ->
            tab.setCustomView(R.layout.tab_view_simple)
            tab.customView!!.findViewById<TextView>(R.id.tab_text).text = titles[position]
            tab.view.setBackgroundColor(
                ContextCompat.getColor(
                    requireContext(),
                    android.R.color.transparent
                )
            )
        }.attach()
    }

    inner class JewelTeypedTabAdatper(fragment: Fragment) : FragmentStateAdapter(fragment) {
        override fun getItemCount(): Int = titles.size

        override fun createFragment(position: Int): Fragment {
            val bundle = bundleOf(Constants.key_jewel_type to position)
            return JewelListFragment.newInstance(bundle)
        }

    }
}